#!/bin/bash

# Docker镜像源配置脚本
# 用于解决国内拉取Docker镜像慢或超时的问题

set -e

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

info() { echo -e "${GREEN}[INFO]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; }

echo "=========================================="
echo "  Docker镜像源配置"
echo "=========================================="
echo ""

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then 
    error "请使用root权限运行此脚本"
    echo "使用方法: sudo ./docker-setup-mirror.sh"
    exit 1
fi

# 备份原配置
if [ -f /etc/docker/daemon.json ]; then
    info "备份原有配置..."
    cp /etc/docker/daemon.json /etc/docker/daemon.json.backup.$(date +%Y%m%d_%H%M%S)
fi

# 创建Docker配置目录
mkdir -p /etc/docker

# 写入镜像源配置
info "配置Docker镜像源..."
cat > /etc/docker/daemon.json << 'EOF'
{
  "registry-mirrors": [
    "https://docker.m.daocloud.io",
    "https://docker.1panel.live",
    "https://docker.awsl9527.cn",
    "https://dockerpull.org",
    "https://dockerhub.icu",
    "https://hub.rat.dev"
  ],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m",
    "max-file": "3"
  },
  "storage-driver": "overlay2"
}
EOF

info "配置文件已创建: /etc/docker/daemon.json"

# 重启Docker服务
info "重启Docker服务..."
systemctl daemon-reload
systemctl restart docker

# 验证配置
info "验证配置..."
sleep 2

if docker info | grep -A 10 "Registry Mirrors" > /dev/null 2>&1; then
    echo ""
    echo "=========================================="
    echo -e "${GREEN}配置成功！${NC}"
    echo "=========================================="
    echo ""
    info "当前镜像源配置："
    docker info | grep -A 10 "Registry Mirrors"
    echo ""
    info "现在可以正常拉取镜像了"
    echo "测试命令: docker pull mysql:8.0"
else
    warn "无法验证镜像源配置，但配置文件已创建"
fi

echo ""
info "如需恢复原配置，备份文件位于: /etc/docker/daemon.json.backup.*"

